/**
 * FormFieldFiles
 */
layui.define(['FormField', 'yunj', 'upload'], function (exports) {

    let FormField = layui.FormField;
    let $ = layui.jquery;
    let upload = layui.upload;

    class FormFieldFiles extends FormField {

        constructor(options = {}) {
            super(options);
            // 上传操作元素elem
            this.upload_action_elem = `#${this.id} .files-upload-box .upload-action-elem`;
            // 文件预览容器dom元素对象
            this.files_preview_box_el = null;
            // 上传文件
            this.upload_files = {};
            // 上传进度的数据
            this.upload_progress_data = {};
            // 上传进度的定时器
            this.upload_progress_timer = {};
        }

        defineExtraArgs() {
            let that = this;
            return {
                max: 9,
                size: yunj.config("file.upload_file_size"),
                ext: yunj.config("file.upload_file_ext"),
                text: "文件上传",
                disabled: false
            };
        }

        handleArgs(args) {
            if (args.verify.indexOf("array") === -1)
                args.verify += (args.verify ? "|" : "") + "array";
            return args;
        }

        layoutControl() {
            let that = this;
            let controlHtml = `<div class="files-upload-box">
                                    <div class="files-select-box" title="${that.args.disabled ? '禁用' : '选择文件上传'}">
                                        <i class="layui-icon layui-icon-upload"></i>
                                        <span>${that.args.text}</span>
                                    </div>
                                    <i class="upload-action-elem"></i>
                                </div>`;
            return `<div class="layui-input-inline yunj-form-item-control">${controlHtml}</div>`;
        }

        // 设置字段简介
        layoutDesc() {
            let that = this;
            return `<div class="yunj-form-item-desc">允许上传大小不超过 ${that.args.size}MB 且格式为 ${that.args.ext} 的文件，允许最大上传数 ${that.args.max}。${that.args.desc || ""}</div>`;
        }

        setValue(val = '') {
            let that = this;
            that.setFilesPreviewBoxLayout(val);
        }

        getValue() {
            let that = this;
            let files = [];
            $(that.files_preview_box_el).find('.files-preview-item-box').each(function () {
                let name = $(this).find('.files-preview-item-input').val();
                if (!name || !yunj.isString(name) || name.length > 2000) return true;
                let url = $(this).find('.files-preview-item-action-box .files-item-download-btn').data('url');
                if (!url || !yunj.isString(url) || url.length > 2000) return true;
                let file = {name: yunj.fileNameExt(name, url), url: url};
                files.push(file);
            });
            return files.length > 0 ? files : "";
        }

        setFilesPreviewBoxLayout(files = '') {
            let that = this;
            if (yunj.isString(files) && files.length > 0)
                files = yunj.isJson(files) ? JSON.parse(files) : [];
            if (!yunj.isArray(files)) files = [];

            if (!that.files_preview_box_el) {
                that.fieldBoxEl.find('.files-upload-box').prepend('<div class="files-preview-box"></div>');
                that.files_preview_box_el = that.fieldBoxEl.find('.files-upload-box .files-preview-box');
            }

            let content = '';
            for (let i = 0, l = files.length; i < l; i++) {
                let file = files[i];
                content += `<div class="files-preview-item-box">
                                <input type="text" class="layui-input files-preview-item-input" value="${file.name}" placeholder="文件名称" ${that.args.disabled ? 'readonly' : ''}>
                                <span class="files-preview-item-action-box">
                                    <i class="layui-icon layui-icon-download-circle files-preview-item-action files-item-download-btn" title="下载:${file.name}" data-url="${file.url}"></i>
                                    <i class="layui-icon layui-icon-delete files-preview-item-action files-item-delete-btn" title="${that.args.disabled ? '禁用' : '删除'}"></i>
                                </span>
                            </div>`;
            }
            that.files_preview_box_el.html(content);
        }

        add_files_preview_box_layout() {
            let that = this;
            let content = '';
            for (let index in that.upload_files) {
                if (!that.upload_files.hasOwnProperty(index)) continue;
                let name = that.upload_files[index].name;
                content += `<div class="files-preview-item-box" data-index="${index}">
                                <input type="text" class="layui-input files-preview-item-input" value="${name}" placeholder="文件名称" readonly>
                                <span class="files-preview-item-action-box">
                                    <i class="files-preview-item-action files-preview-item-upload-progress">0%</i>
                                </span>
                            </div>`;
            }
            that.files_preview_box_el.append(content);
            for (let index in that.upload_files) {
                if (!that.upload_files.hasOwnProperty(index)) continue;
                that.upload_progress_start(index);
            }
        }

        // 设置上传进度数据
        set_upload_progress_data(index, args = {}) {
            let defArgs = {
                elem: null,
                rate_num: 0
            };
            args = yunj.objSupp(args, defArgs);
            let that = this;
            if (!that.upload_progress_data.hasOwnProperty(index)) that.upload_progress_data[index] = defArgs;
            that.upload_progress_data[index].elem = that.upload_progress_data[index].elem || that.files_preview_box_el.find(`.files-preview-item-box[data-index=${index}]`);
            that.upload_progress_data[index].rate_num = args.rate_num;

            that.upload_progress_data[index].elem.find('.files-preview-item-upload-progress').html(args.rate_num + '%');
        }

        // 上传开始
        upload_progress_start(index) {
            let that = this;

            that.set_upload_progress_data(index, {
                rate_num: 0,
            });
            that.upload_progress_timer[index] = setInterval(function () {
                let rateNum = that.upload_progress_data[index].rate_num;
                rateNum = rateNum + Math.random() * 10 | 0;
                rateNum = rateNum > 99 ? 99 : rateNum;

                that.set_upload_progress_data(index, {
                    rate_num: rateNum,
                });
            }, 300 + Math.random() * 1000);
        }

        // 上传结束
        upload_progress_end(index, data) {
            let that = this;

            clearInterval(that.upload_progress_timer[index]);

            that.set_upload_progress_data(index, {
                rate_num: 100,
            });
            let name = data.fileName;
            let url = data.url;
            that.upload_progress_data[index].elem.find('.files-preview-item-input').val(name);
            that.upload_progress_data[index].elem.find('.files-preview-item-input').attr('readonly', false);
            let actionBoxContent = `<i class="layui-icon layui-icon-download-circle files-preview-item-action files-item-download-btn" title="下载:${name}" data-url="${url}"></i>
                                  <i class="layui-icon layui-icon-delete files-preview-item-action files-item-delete-btn" title="删除"></i>`;
            that.upload_progress_data[index].elem.find('.files-preview-item-action-box').html(actionBoxContent);
            setTimeout(function () {
                that.delete_upload_item_data(index);
            }, 1000);
        }

        // 上传错误
        upload_error(index, tips = '') {
            let that = this;
            if (!that.upload_progress_data.hasOwnProperty(index)) return false;
            if (tips.length <= 0) return false;
            let actionBoxContent = `<i class="layui-icon layui-icon-speaker files-preview-item-action" title="${tips}" style="color:#FF5722;"></i>
                                  <i class="layui-icon layui-icon-delete files-preview-item-action files-item-delete-btn" title="删除"></i>`;
            that.upload_progress_data[index].elem.find('.files-preview-item-action-box').html(actionBoxContent);
            that.delete_upload_item_data(index);
        }

        // 删除上传数据
        delete_upload_item_data(index) {
            let that = this;
            if (that.upload_progress_timer.hasOwnProperty(index)) {
                clearInterval(that.upload_progress_timer[index]);
                delete that.upload_progress_timer[index];
            }
            if (that.upload_progress_data.hasOwnProperty(index)) {
                delete that.upload_progress_data[index];
            }
        }

        // 设置上传事件绑定
        set_upload_event_bind() {
            let that = this;

            let args = {
                elem: `#${that.id} .files-select-box`,
                url: yunj.fileUploadUrl(),
                accept: 'file',
                exts: that.args.ext.replace(/,/g, '|'),
                auto: false,
                bindAction: that.upload_action_elem,
                field: 'file',
                size: that.args.size * 1024,
                multiple: true,
                drag: false,
                choose: function (obj) {
                    if (!yunj.isObj(that.upload_files) || !yunj.isEmptyObj(that.upload_files)) {
                        yunj.msg('待上传完成后，执行此操作');
                        return false;
                    }
                    that.upload_files = obj.pushFile();

                    // 判断是否超过限制数量
                    let count = (that.files_preview_box_el.find('.files-preview-item-box').length | 0) + (Object.keys(that.upload_files).length | 0);
                    if (count > that.args.max) {
                        yunj.msg(`限制最大上传数 ${that.args.max}`);
                        for (let idx in that.upload_files) {
                            if (!that.upload_files.hasOwnProperty(idx)) continue;
                            delete that.upload_files[idx];
                        }
                        return false;
                    }

                    that.add_files_preview_box_layout();
                    $(that.upload_action_elem).click();
                },
                done: function (res, index, upload) {
                    delete that.upload_files[index];
                    if (res.errcode !== 0) {
                        that.upload_error(index, res.msg);
                        return false;
                    }
                    that.upload_progress_end(index, res.data);
                }
            };

            upload.render(args);
        }

        defineExtraEventBind() {
            let that = this;

            if (!that.args.disabled) {
                // 上传
                that.set_upload_event_bind();

                // 删除
                that.fieldBoxEl.on('click', '.files-preview-item-box .files-preview-item-action-box .files-item-delete-btn', function (e) {
                    $(this).parents('.files-preview-item-box').remove();
                    e.stopPropagation();
                });
            }

            // 下载
            that.fieldBoxEl.on('click', '.files-preview-item-box .files-preview-item-action-box .files-item-download-btn', function (e) {
                let name = $(this).parent('.files-preview-item-action-box').prev('.files-preview-item-input').val();
                if (!name || !yunj.isString(name) || name.length > 2000) return false;
                let url = $(this).data('url');
                if (!url || !yunj.isString(url) || url.length > 2000) return true;
                name = yunj.fileNameExt(name, url);
                yunj.download({name: name, url: url});
            });
        }

    }

    exports('FormFieldFiles', FormFieldFiles);
});